package com.example.blog.controller;

import com.example.blog.constants.Constants;
import com.example.blog.model.BlogInfo;
import com.example.blog.service.BlogService;
import com.example.blog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController  {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getList")
    public List<BlogInfo>getList(){
        log.info( "获取博客列表 ");
        return blogService.getList();

    }
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId ,HttpServletRequest request){
        log.info( "获取博客详细信息 ");
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = (Integer) JwtUtils.getIdByToken(token);
        BlogInfo blogDetail= blogService.getBlogDetail(blogId);
        if(userId!=null&&userId==blogDetail.getUserId()){
            blogDetail.setLoginUser(true);
        }else {
            blogDetail.setLoginUser(false);
        }
        return blogDetail;
    }
    @RequestMapping("/add")
    public Boolean addBook(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        log.info("添加图书");
        if(!StringUtils.hasLength(blogInfo.getContent())||!StringUtils.hasLength(blogInfo.getTitle())){
            return false;
        }
        //从token中获取登录用户id
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = (Integer) JwtUtils.getIdByToken(token);
        blogInfo.setUserId(userId);

        return blogService.insertBook(blogInfo);

    }
    @RequestMapping("/delete")
    public Boolean delete( Integer blogId){
        log.info("删除博客，blog{}",blogId);
        if(blogId<=0){
            return false;
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);//删除
        blogService.update(blogInfo);
        return true;


    }
    @RequestMapping("/update")
    public Boolean delete(BlogInfo blogInfo){
        log.info("更新博客",blogInfo);
        if(blogInfo.getId()==null||!StringUtils.hasLength(blogInfo.getTitle())||!StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }
        blogService.update(blogInfo);
        return true;


    }
}

